<template>
  <div class="hello">
    <!-- form card -->
    <el-card
      v-for="(e, i) in dataModel"
      v-if="e.formComponent && e.formComponent.length"
      :key="e.index"
      :class="e.formStyle || 'box-card'"
    >
      <div slot="header" class="clearfix">
        <span>{{ e.formName }}</span>
      </div>
      <el-form
        :ref="dataModel[i].formRef"
        :inline="true"
        :model="dataModel[i]['formModel']"
        class="demo-form-inline"
      >
        <el-col :span="24">
          <el-col
            v-for="item in e.formComponent"
            :key="item.model"
            :span="item.type == 'upload' || item.type == 'mainupload' ? 24 : 5"
          >
            <el-form-item
              label-width="120px"
              :prop="item.model"
              :rules="item.rules"
              :label="item.label"
              class="postInfo-container-item"
            >
              <!-- input-->
              <el-input
                v-if="item.type == 'input'"
                v-model="dataModel[i]['formModel'][item.model]"
                :maxlength="item.maxlength"
                style="width: 150px"
                class="filter-item"
                @keyup.enter.native="item.keyUpEnter"
              />
              <el-input
                v-if="item.type == 'inputNumber'"
                v-model="dataModel[i]['formModel'][item.model]"
                style="width: 150px"
                class="filter-item"
                :maxlength="item.maxlength"
                oninput="value=value.replace(/[^0-9]/g,'')"
                @keyup.enter.native="item.keyUpEnter"
              />
              <el-input
                v-if="item.type == 'inputFloat'"
                v-model="dataModel[i]['formModel'][item.model]"
                :maxlength="item.maxlength"
                style="width: 150px"
                class="filter-item"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                @keyup.enter.native="item.keyUpEnter"
              />
              <el-select
                v-if="item.type == 'select1'"
                v-model="dataModel[i]['formModel'][item.model]"
                :placeholder="item.placeholder || ''"
                clearable
                style="width: 150px"
                class="filter-item"
              >
                <el-option
                  v-for="e in setSelectOptions(
                    dataModel[i]['formComponent'],
                    item.model
                  )"
                  :key="e"
                  :label="e"
                  :value="e"
                />
              </el-select>
              <!-- select-->
              <el-select
                v-if="item.type == 'select'"
                v-model="dataModel[i]['formModel'][item.model]"
                :placeholder="item.placeholder || ''"
                clearable
                style="width: 150px"
                class="filter-item"
              >
                <el-option
                  v-for="e in item.options"
                  :key="e.value"
                  :label="e.lable"
                  :value="e.value"
                />
              </el-select>
              <!--cascader -->
              <el-cascader
                v-if="item.type === 'cascader'"
                v-model="dataModel[i]['formModel'][item.model]"
                :options="item.options"
                :props="
                  item.checkStrictly
                    ? { emitPath: false, checkStrictly: false }
                    : { emitPath: false, checkStrictly: true }
                "
                clearable
                style="width: 150px"
                class="filter-item"
              />
              <el-cascader
                v-if="item.type === 'organization'"
                v-model="dataModel[i]['formModel'][item.model]"
                :options="setOptions(item.type)"
                :props="{ emitPath: false, checkStrictly: true }"
                clearable
                style="width: 150px"
                class="filter-item"
              />
              <!-- datepicker-->
              <el-date-picker
                v-if="item.type == 'datePicker'"
                v-model="dataModel[i]['formModel'][item.model]"
                style="width: 150px"
              />
              <el-date-picker
                v-if="item.type == 'datePicker1'"
                v-model="dataModel[i]['formModel'][item.model]"
                :type="translateType(dataModel[i]['formComponent'], item.model)"
                value-format="yyyy-MM-dd"
                style="width: 150px"
              />
              <!-- dateRangepicker -->
              <el-date-picker
                v-if="item.type == 'dateRangepicker'"
                v-model="dataModel[i]['formModel'][item.model]"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
              <el-upload
                v-if="item.type == 'mainupload'"
                :ref="item.model"
                v-model="dataModel[i]['formModel'][item.model]"
                class="upload-demo"
                action="/minio/minio/upload"
                :limit="1"
                :on-exceed="handleExceed"
                :headers="headers"
                :file-list="fileList[item.model]"
                :on-success="
                  (a, b, c) => uploadFileSuccess(a, b, c, item.model)
                "
                :before-upload="beforeAvatarUpload"
                list-type="picture"
              >
                <el-button size="small" type="primary">上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  请上传一张设备主图,建议比例3:2,支持格式:jpg、jpeg、png,不超过10M
                </div>
              </el-upload>
              <el-upload
                v-if="item.type == 'upload'"
                :ref="item.model"
                v-model="dataModel[i]['formModel'][item.model]"
                class="upload-demo"
                action="/minio/minio/upload"
                :limit="20"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :headers="headers"
                multiple="true"
                :file-list="fileList[item.model]"
                :on-success="
                  (a, b, c) => uploadFileSuccess(a, b, c, item.model)
                "
              >
                <el-button size="small" type="primary">上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  1.请上传设备档案资料，支持格式：doc、docx、pdf、jpg、jpeg、png。
                  <br />
                  2.最多可上传20个文件，单个文件不大于50M。
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form>
    </el-card>
    <!-- 提交 -->
    <el-row class="edit-form-button" type="flex" justify="center">
      <el-button type="primary" @click="enterForm">提交审批</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-row>
  </div>
</template>

<script>
import Cookies from "js-cookie";
const Auth = Cookies.get("Admin-Token");
export default {
  props: ["dataModel", "submitHandle"],
  data() {
    return {
      // dataModel: this.dataModel.formComponent,
      // listQuery: this.dataModel.formComponent,
      formRules: this.dataModel.formRules,
      downloadLoading: false,
      fileList: {
        drawPath: [],
        archives: [],
      },
      headers: { Authorization: "Bearer " + Auth },
      //  dataModel:[{
      //    formRef:'formFirst',//表单ref
      //    formModel:this.dataModel.formModel,//表单model
      //   formComponent:this.dataModel.formComponent,
      //    formName:'表单A'//表单标题
      //   },{
      //   formRef:'formSecond',
      //    formModel:this.dataModel.formModel,
      //     formComponent:this.dataModel.formComponent,
      //    formName:'表单B'
      //   },{
      //     formRef:'formThird',
      //    formModel:this.dataModel.formModel,
      //     formComponent:this.dataModel.formComponent,
      //    formName:'表单C'
      //   }],
    };
  },
  watch: {
    "dataModel.0.formModel.drawPath": {
      handler(newData, oldData) {
        if (oldData) {
          // 只负责进行初始化，如果oladData已经有值则不再触发
          return;
        }
        console.log(newData, "编辑设备台账");
        const drawPath = newData;
        this.fileList.drawPath = drawPath
          ? [
              {
                name: "设备主图",
                url: drawPath,
              },
            ]
          : [];
      },
      deep: true,
      immediate: true,
    },
    "dataModel.2.formModel.archives": {
      handler(newData, oldData) {
        if (oldData && oldData.length) {
          // 只负责进行初始化，如果oladData已经有值则不再触发
          return;
        }
        console.log(newData, "编辑设备台账");
        const archives = newData;
        archives &&
          archives.forEach(function (e) {
            e.url = e.viewPath;
            e.name = e.archiveName;
          });
        this.fileList.archives = archives && !archives.legnth ? archives : [];
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    console.log(this, "111");
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning("上传文件数达到上限");
    },
    beforeAvatarUpload(file) {
      var FileExt = file.name.replace(/.+\./, "");
      if (["jpg", "jpeg", "png"].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: "warning",
          message: "请上传后缀名为jpg、png、jpeg的图片",
        });
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过10MB!");
        return false;
      }

      return true;
    },
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, "");
      if (
        ["doc", "docx", "pdf", "jpg", "jpeg", "png"].indexOf(
          FileExt.toLowerCase()
        ) === -1
      ) {
        this.$message({
          type: "warning",
          message: "请上传后缀名为doc、docx、pdf、jpg、png、jpeg的图片",
        });
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 50;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过50MB!");
        return false;
      }

      return true;
    },
    listTotree(list) {
      var listData = [...list];
      var map = {};
      var node;
      var tree = [];
      var i;
      for (i = 0; i < listData.length; i++) {
        map[listData[i].id] = listData[i];
        // listData[i]["value"]= listData[i].typeId||listData[i].organId
        // listData[i]["label"]= listData[i].typeName|| listData[i].organName
        // listData[i].children = [];
      }
      for (i = 0; i < listData.length; i++) {
        node = listData[i];
        if (node.parentId == 0) {
          tree.push(node);
        } else {
          // map[node.parentId].children?map[node.parentId].children:map[node.parentId].children=[] //这里是为了配合ele组件
          // map[node.parentId].children.push(node);
          // delete node.children
        }
      }
      return tree;
    },
    setOptions(type) {
      if (type == "organization") {
        return this.listTotree(this.$store.state.app.allCode.department);
      }
    },
    setSelectOptions(array, modelName) {
      let data;

      array.forEach((e) => {
        if (e.model == modelName) {
          data = e.fieldRuleType ? e.fieldRuleType.split(",") : [];

          return;
        }
      });

      return data;
    },
    translateType(array, modelName) {
      let data;
      array.forEach((e) => {
        if (e.model == modelName) {
          data = e;
          return;
        }
      });

      return data.format;
    },
    uploadFileSuccess(res, file, fileList, type) {
      setTimeout(() => {
        console.log(fileList, "fileList");
        let fileList1 = [...fileList];
        // 把fileList组装成后端需要的数据,这里根据透传的type来区分2个上传
        if (type == "drawPath") {
          // 设备主图 只有一张

          this.dataModel[0].formModel.drawPath = file.response.data.viewPath;
        } else {
          // 档案设备
          const data = [];
          fileList1.map((item) => {
            const viewPath = item.response
              ? item.response.data.viewPath
              : item.viewPath;
            const path = item.response
              ? item.response.data.path
              : item.archivePath;
            data.push({
              archivePath: path,
              viewPath: viewPath,
              archiveName: item.name,
            });
          });
          this.dataModel[2].formModel.archives = data;
        }

        console.log("archives", this.dataModel[2].formModel.archives);
      }, 1000);
    },
    cancelForm() {
      this.$store.dispatch("tagsView/delVisitedView", {
        path: this.$route.fullPath,
      });
      this.$router.push("/device-basic/index");
    },
    enterForm() {
      // 动态表单提交
      const arrForm = []; // 哪些表单需要做校验
      const arrModel = []; // 表单的值
      const newArr = []; // 承接promise的返回结果
      const _self = this;
      this.dataModel.forEach((item, index) => {
        // 将有权限的表单做校验等等
        console.log("+++", item.formRef);

        checkForm(item.formRef); // 校验
        arrModel.push(item); // 需要校验的表单的值
      });
      function checkForm(arrName) {
        // 根据form表单的ref，动态生成promise，再对其坐表单校验，都通过了再去做处理
        console.log(_self.$refs[arrName], "-----");
        if (!_self.$refs[arrName]) {
          return;
        }
        var result = new Promise(function (resolve, reject) {
          _self.$refs[arrName][0].validate((valid) => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        });
        newArr.push(result); // push 得到promise的结果
      }
      Promise.all(newArr)
        .then(function () {
          // 都通过了
          console.log(arrModel);
          console.log("恭喜，表单全部验证通过");

          _self.submitHandle(arrModel);
        })
        .catch(function (e) {
          console.log("表单验证失败", e);
          // _self.submitHandle(arrModel);
          console.log("err");
        });
    },
  },
};
</script>

<style scoped>
.box-card {
  border: 0px;
  background-color: #fff;
  overflow: hidden;
  color: #303133;
  box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);
}
.box-margin-card {
  margin-top: 20px;
  border: 0px;
  background-color: #fff;
  overflow: hidden;
  color: #303133;
  box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);
}
.edit-form-button {
  margin: 20px 0;
}
</style>
